package com.neiru.divider.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.neiru.divider.bean.Player;
import com.neiru.divider.dao.constants.PlayerConstants;
import com.neiru.divider.dao.helper.DatabaseHelper;

public class PlayerDao {
	private Context context;
	private DatabaseHelper dbHelper;
	private SQLiteDatabase db;
	public PlayerDao(Context context) {
		this.context = context;
	}
	public PlayerDao open() throws SQLException {
		dbHelper = new DatabaseHelper(context);
		db = dbHelper.getWritableDatabase();
		return this;
	}
	
	public PlayerDao close() {
		db.close();
		return this;
	}
	
	public Player getPlayer() {
		Cursor cursor = db.query(PlayerConstants.DATABASE_PLAYER_TABLE, 
				new String[] {PlayerConstants.KEY_LAST_LEVEL, PlayerConstants.KEY_SCORE},
				null, null, null, null, null, null);
		if (cursor != null && cursor.getCount()> 0) {
			cursor.moveToFirst();
		} else {
			return null;
		}
		if(cursor.isAfterLast() || cursor.isBeforeFirst()) {
			return null;
		}
		Player player = new Player();
		player.setLastLevel(
				cursor.getInt(
						cursor.getColumnIndexOrThrow(
								PlayerConstants.KEY_LAST_LEVEL)));
		player.setScore(cursor.getInt(
						cursor.getColumnIndexOrThrow(
								PlayerConstants.KEY_SCORE)));
		return player;
	}
	
	public void updatePlayer(Player player) {
		deletePlayer();
		createPlayer(player);
	}
	public void createPlayer(Player player) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(PlayerConstants.KEY_LAST_LEVEL, player.getLastLevel());
		initialValues.put(PlayerConstants.KEY_SCORE, player.getScore());
		db.insert(PlayerConstants.DATABASE_PLAYER_TABLE, null, initialValues);
	}
	private void deletePlayer() {
		String[] stringVacio = {};
		db.delete(PlayerConstants.DATABASE_PLAYER_TABLE,null,stringVacio);
	}
	
}
